package com.tfswx.jcyw.dmzc.component;

import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

public final class TranslucenceJPanel extends JPanel {
    private final byte[] imgBytes;
    private float transparency;

    public TranslucenceJPanel(byte[] imgBytes) {
        super();
        this.imgBytes = imgBytes;
        this.setOpaque(false);
    }

    public void setTransparent(float transparency) {
        this.transparency = transparency;
        this.repaint();
    }

    @Override
    @SneakyThrows
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        if (g2d == null) {
            throw new NullPointerException("null cannot be cast to non-null type java.awt.Graphics2D");
        }
        g2d.setComposite(AlphaComposite.SrcOver.derive(this.transparency));
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(this.imgBytes));
        g2d.drawImage(image, 0, 0, null);
        g2d.setColor(this.getBackground());
        g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
        g2d.dispose();
    }
}
